package login

import (
	"gin_demo/internal/consts"
	"gin_demo/internal/model"
	"gin_demo/utility"
	"strconv"

	"github.com/gin-gonic/gin"
)

func Login(ctx *gin.Context, req LoginReq) {
	// 登录
	user := model.AdminInfo{}
	tx := consts.App.DB.Where("user_name=?", req.UserName).First(&user)
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "登录失败，用户名或密码错误")
	} else {
		// 校验密码
		if b := utility.BcryptMakeCheck([]byte(req.PassWord), user.Password); !b {
			utility.Fail(ctx, "登录失败，用户名或密码错误")
		} else {
			// 生成token
			token, _ := utility.CreateToken(user)
			// 返回token
			// timer :=
			userInfo := LoginRes{
				Id:       user.ID,
				UserName: user.UserName,
				IsAdmin:  user.IsAdmin,
				RoleIds:  user.RoleIds,
				Token:    token,
				// ExpiresAt: timer,
			}

			/*将token存入redis*/
			utility.RedisSet(strconv.Itoa(int(user.ID)), token)
			utility.Success(ctx, userInfo)
		}
	}

}
